package com.lyd.lydblog.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;

import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import com.lyd.lydblog.bean.Row;
import com.lyd.lydblog.bean.Worksheet;
import com.lyd.lydblog.entity.User;
import com.lyd.lydblog.service.UserService;

@Controller
public class UserController {

	Logger log = LogManager.getLogger(getClass());
	public static int i;
	
	@Resource
	UserService userService;
	
	@RequestMapping("index")
	public String index(){		
		return "index";
	} 
	
	@PostMapping("login")
	public String login(HttpServletRequest request){
		String kaptcha = (String) request.getParameter("kaptcha");
		String verifyCode =  (String) request.getSession().getAttribute("verifyCode");
		if(kaptcha.equals(verifyCode)){
			return findAllUserList(request);			
		}
		return "index";
	} 
	@RequestMapping("loginGet")
	public String loginGet(HttpServletRequest request,@PathVariable String kaptcha){
		//String kaptcha = (String) request.getParameter("kaptcha");
		String verifyCode =  (String) request.getSession().getAttribute("verifyCode");
		if(kaptcha.equals(verifyCode)){
			return findAllUserList(request);			
		}
		return "index";
	} 
	
	/**
	 * 获取单一对象
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping("/user/{id}")
	public String getUser(HttpServletRequest request, @PathVariable("id") Long id){
		User user = userService.selectByPrimaryKey(id);
		request.setAttribute("user", user);
		return "user";
	}
	
	/**
	 * 获取列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/allusers")
	public String findAllUserList(HttpServletRequest request){
		List<User> users=userService.findAllUserList();
		request.setAttribute("users", users);
		log.info(users);
		return "users";
	}
	
	/**
	 * 获取单一对象
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping("/user/error")
	public String getUserError(HttpServletRequest request){
		int i = 0;
		i=1/0;
		return "user";
	}
	
	@RequestMapping("testExp")
	@ResponseBody
	public void exp(HttpServletRequest request) throws FileNotFoundException{
		 //String templateHead = "template/excel/head";
		 String templateHead = "excel/head";
		 String head = render(templateHead,new HashMap<String,Object>());
		long startTimne = System.currentTimeMillis();
       // StringTemplateGroup stGroup = new StringTemplateGroup("stringTemplate");

        //写入excel文件头部信息
       // StringTemplate head =  stGroup.getInstanceOf("template/excel/head");
        File file = new File("C:\\data\\bak\\output.xls");
        PrintWriter writer = new PrintWriter(new BufferedOutputStream(new FileOutputStream(file)));
        writer.print(head.toString());
        writer.flush();

        int sheets = 1;
        //excel单表最大行数是65535
        int maxRowNum = 666;

        //写入excel文件数据信息
        for(int i=1;i<sheets+1;i++){
            //StringTemplate body =  stGroup.getInstanceOf("template/excel/body");
            Worksheet worksheet = new Worksheet();
            worksheet.setSheet(" "+(i+1)+" ");
            worksheet.setColumnNum(3);
            worksheet.setRowNum(maxRowNum);
            List<Row> rows = new ArrayList<>();
            Row row0 = new Row();
            row0.setName1("姓名");
            row0.setName2("年龄");
            row0.setName3("地址");
            rows.add(row0);
            for(int j=1;j<maxRowNum;j++){
                Row row = new Row();
                row.setName1(""+new Random().nextInt(100000));
                row.setName2(""+j);
                row.setName3(i+""+j);
                rows.add(row);
            }
            worksheet.setRows(rows);
            

        	//String templateBody = "template/excel/body";
            String templateBody = "excel/body";
        	Map m = new HashMap();
        	m.put("sheet", worksheet.getSheet());
        	m.put("columnNum", worksheet.getColumnNum());
        	m.put("rowNum", worksheet.getRowNum());
        	m.put("rows", worksheet.getRows());
        	String body = render(templateBody,m);
//            body.setAttribute("worksheet", worksheet);
//        	Context context = new Context();
//            context.setVariables(worksheet);
//            return engine.process(templateBody,context);
        	System.out.println(head.toString()+body.toString());
            writer.print(body.toString());
            writer.flush();
            rows.clear();
            rows = null;
            worksheet = null;
            body = null;
            Runtime.getRuntime().gc();
            //System.out.println("正在生成excel文件的 sheet"+(i+1));
        }

        //写入excel文件尾部
        writer.print("</Workbook>");
        writer.flush();
        writer.close();
        System.out.println("生成excel文件完成");
        long endTime = System.currentTimeMillis();
        System.out.println("用时="+((endTime-startTimne)/1000)+"秒");
		
	} 

	//private final static TemplateEngine engine=new TemplateEngine();
	@Autowired
	private SpringTemplateEngine thymeleaf;
	public String render(String template, Map<String,Object> params){
        Context context = new Context();
        context.setVariables(params);
        //thymeleaf.pr
        return thymeleaf.process(template,context);
    }
}
